using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MapListPanelData
{
    public List<MapListItemData> itemDatas;
}

public interface IMapListPanel
{
    void OnSelectItem(MapListItem item);
    void OnClickGoBack();

}
public class MapListPanel : PanelCommon {

    MapListPanelData m_Data;

    List<MapListItem> m_ItemList = new List<MapListItem>();
    public List<MapListItem> itemList => m_ItemList;

    //public Transform[] itemLocations;
    public Transform itemParent;
    
    IMapListPanel m_IMapListPanel;

    public MapListItem MapListItemPref;

    public override void Awake()
    {
        base.Awake();
        
        if(MapListItemPref)
            MapListItemPref.gameObject.SetActive(false);

        /*foreach (var location in itemLocations)
        {
            for (int i = 0; i < location.childCount; i++)
            {
                Destroy(location.GetChild(i).gameObject);
            }
        }*/
    }



    public void Init(MapListPanelData data, IMapListPanel MapListPanelListener)
    {
        m_Data = data;
        m_IMapListPanel = MapListPanelListener;
        
        UnityFunctions.ClearList(m_ItemList);

        if (data != null)
        {
            for(int i = 0; i < data.itemDatas.Count; i++)
            {
                if (data.itemDatas[i] == null)
                {
                    GameDebug.LogError("data.itemDatas[i] == null");
                    continue;
                }

                Transform location = itemParent;//i<itemLocations.Length? this.itemLocations[i]:this.transform;
                
                var item = Instantiate(MapListItemPref, location);
                item.gameObject.SetActive(true);
                item.transform.localPosition = Vector3.zero;
                m_ItemList.Add(item);

                try
                {
                    item.Init(data.itemDatas[i],OnSelectItem);
                }
                catch (Exception e)
                {
                    GameDebug.LogError(e);
                }

                //GameDebug.Log($"list add item:{data.itemDatas[i].playerId}");
            }

        }
        
    }

    public void OnSelectItem(MapListItem item)
    {
        m_IMapListPanel?.OnSelectItem(item);
    }

    public new void GoBack()
    {
        this.m_IMapListPanel?.OnClickGoBack();
    }

}